var currentOverlay;
var currentOverlayExistAsParent = false;
var currentOverlayTimeout;
var currentOverlayEventHolder;

$(document).ready(function(e) {
	
	$("div.overlay-callout-button").live('click',function()
	{
		$(this).parent(".overlay-callout-panel").find('div.overlay-callout-content').each(function(index, element) {
			if($(this).css('display') == 'none')
			{	
					if($(this).parents('div[data-role="header"]').length == 1){
						$(this).css('position','fixed');				
					}
					else{
						$(this).css('position','absolute');	
					}
					
           		 $(this).css('display','block').fadeOut(0).fadeIn(300);
				
				closeOverlayPanel($(this));
				
				 
				 
				$('*').bind('click',function(e){
					currentOverlayEventHolder = e;
        			if($(this).parents('.overlay-callout-panel').length == 1){
						currentOverlayExistAsParent = true;
						
					}
					
					if(currentOverlayTimeout != null)
							clearTimeout(currentOverlayTimeout);							
					currentOverlayTimeout = setTimeout(removeCurrentOverlay,300);
					
				});
			}
			else{
				closeOverlayPanel();
				 $('*').unbind(currentOverlayEventHolder);
			}
			
        }); 
	});
	
	
});

function removeCurrentOverlay(){
	if(currentOverlayExistAsParent == false){
		closeOverlayPanel();
		if(currentOverlayEventHolder != null)
			$('*').unbind(currentOverlayEventHolder);
	}
	currentOverlayExistAsParent = false;
	
}

function closeOverlayPanel(newObject){
	if(currentOverlay != null){
		currentOverlay.fadeOut(200,function(){
			currentOverlay.css('display','none');
			currentOverlay = newObject;
		});
	}
	else{
		currentOverlay = newObject;
	}
}

